import Mock from 'mockjs';

const Random = Mock.Random;

// 使用全局变量存储用户数据
let users = [];
for (let i = 0; i < 100; i++) {
    users.push({
        id: i + 1,
        name: Random.name(),
        age: Random.integer(18, 60),
        sex: Random.integer(0, 1) === 0 ? '男' : '女',
        email: Random.email(),
        phone: Random.string('number', 11)
    });
}

Mock.mock('/api/users', 'get', (options) => {
    // 解析请求体中的参数
    const body = JSON.parse(options.body);

    let filteredUsers = JSON.parse(JSON.stringify(users));

    if (body && body.name) {
        filteredUsers = filteredUsers.filter(user => user.name.includes(body.name));
    }

    if (body && body.sex) {
        filteredUsers = filteredUsers.filter(user => user.sex === body.sex);
    }

    return {
        code: 200,
        data: filteredUsers,
    }

});

Mock.mock('/api/users/add', 'post', (options) => {
    const user = JSON.parse(options.body);
    user.id = users.length + 1;
    users.push(user);
    return {
        code: 200,
        data: user,
    };
});

Mock.mock('/api/users/delete', 'post', (options) => {
    const { id } = JSON.parse(options.body);
    const index = users.findIndex(user => user.id === id);
    if (index !== -1) {
        users.splice(index, 1);
        return {
            code: 200,
            data: id,
        };
    }
    return {
        code: 400,
        message: 'User not found',
    };
});

Mock.mock('/api/users/update', 'post', (options) => {
    const updatedUser = JSON.parse(options.body);
    const index = users.findIndex(user => user.id === updatedUser.id);
    if (index !== -1) {
        users[index] = updatedUser;
        return {
            code: 200,
            data: updatedUser,
        };
    }
    return {
        code: 400,
        message: 'User not found',
    };
});
